package com.soundfrequencyapp;

import com.soundfrequencyapp.fft.DoubleFFT_1D;

public class SoundUtil {
	
	public static double calculateFrequency(byte[] audioData, int bufferSize, int sampleRate) {
		int dataSize = bufferSize / 2;
		double[] data = new double[dataSize];
	    final int bytesPerSample = 2; // As it is 16bit PCM
	    final double amplification = 100.0; // choose a number as you like
	    for (int index = 0, floatIndex = 0; index < bufferSize - bytesPerSample + 1; index += bytesPerSample, floatIndex++) {
	        double sample = 0;
	        for (int b = 0; b < bytesPerSample; b++) {
	            int v = audioData[index + b];
	            if (b < bytesPerSample - 1 || bytesPerSample == 1) {
	                v &= 0xFF;
	            }
	            sample += v << (b * 8);
	        }
	        double sample32 = amplification * (sample / 32768.0);
	        data[floatIndex] = sample32;
	    }
		
		int magnitudesArraySize = dataSize / 2;
		double[] magnitudeValues = new double[magnitudesArraySize];
		DoubleFFT_1D fft = new DoubleFFT_1D(dataSize);

		fft.realForward(data);

		for (int i = 0; i < dataSize - 2; i += 2) {
			double f = Math.sqrt(data[i] * data[i] + data[i + 1] * data[i + 1]);
			magnitudeValues[i / 2] = f;
		}

		int maxMagnitudeI = 1;
		double maxMagnitudeValue = magnitudeValues[1];

		for (int i = 1; i < magnitudeValues.length - 1; i++) {
			if (maxMagnitudeValue < magnitudeValues[i]) {
				maxMagnitudeI = i;
				maxMagnitudeValue = magnitudeValues[i];
			}
		}

		float frequency = sampleRate * maxMagnitudeI / (dataSize);

		return frequency;
	}

}
